/**
 * 项目名称：MSH
 * 包名称：com.mt.common.sys.daoImpl
 * 文件名称：PermissionDaoImpl.java
 */
package com.mt.system.daoImpl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;


import org.springframework.stereotype.Repository;

import com.mt.system.dao.PermissionDao;
import com.mt.system.domain.Permission;
import com.mt.system.domain.Role;
import com.mt.system.domain.User;


/**
 * 类名称：PermissionDaoImpl <br>
 * 类描述： <br>
 * 创建人： 马腾 <br>
 * 创建时间：2012-10-18 下午10:36:50 <br>
 */
@Repository
public class PermissionDaoImpl implements PermissionDao {
	
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public Permission addPermission(Permission permission) {
		entityManager.persist(permission);
		return permission;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Permission> getPermissions() {
		String eql = "FROM Permission P " +
					 "LEFT JOIN FETCH P.parent " + 
					 "LEFT JOIN FETCH P.menu " +
					 "LEFT JOIN FETCH P.funct";
		Query query = entityManager.createQuery(eql);
		return query.getResultList();
	}

	@Override
	public List<Permission> getPermissionsByUser(User user) {
		String eql = "select permission FROM User user " +
					 "join user.roles role " +
					 "join role.permissions permission " +
					 "left join fetch permission.parent " +
					 "left join fetch permission.menu " +
					 "left join fetch permission.funct " +
					 "where user.id = :id";
		Query query = entityManager.createQuery(eql);
		query.setParameter("id", user.getId());
		return query.getResultList();
	}

	@Override
	public Permission getPermissionByMark(String mark) {
		String eql = "from Permission p where p.mark = :mark";
		Query query = entityManager.createQuery(eql);
		query.setParameter("mark", mark);
		try {
			return (Permission) query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public List<Permission> getPermissionsByRole(Role role) {
		String eql = "select permission from Role role " +
					 "join role.permissions permission " +
					 "left join fetch permission.parent " +
					 "left join fetch permission.menu " +
					 "left join fetch permission.funct " +
					 "where role.id = :id";
		Query query = entityManager.createQuery(eql);
		query.setParameter("id", role.getId());
		return query.getResultList();
	}
	
}
